<template>
  <div class="rowItem">
    <vue-drag-resize
      v-if="x_end - x_start > 0"
      :isActive="false"
      :w="x_end - x_start"
      :h="height - 5 * 2 - 2"
      :minw="0"
      :minh="height - 5 * 2 - 2"
      :isDraggable="true"
      :sticks="['ml', 'mr']"
      :z="999"
      @resizestop="onResizestop"
      @dragstop="onDragstop"
      @activated="onActivated"
      :key="dragKey"
    >
      <div class="draggable">
        <div>{{ name }}</div>
      </div>
    </vue-drag-resize>
  </div>
</template>

<script setup>
import { ref, watchEffect } from "vue";

const props = defineProps({
  x_start: {
    type: Number,
    default: 0,
  },
  x_end: {
    type: Number,
    default: 0,
  },
  name: {
    type: String,
    default: "",
  },
  rowHeight: {
    type: Number,
    default: 50,
  },
});
const emit = defineEmits([
  "currentRow_update", // 行内左右整体拖动
  "enjambment_update", // 跨行拖动
  "select_update", // 激活项
  "size_update", // 行内左右侧拉动改变大小
]);

let itemWidth = ref("");
let itemLeft = ref("");
let dragKey = ref(0);
let height = ref(50);
// 选中项
let selectItem = ref(null);

watchEffect(() => {
  itemWidth.value = props.x_end - props.x_start + "px";
  itemLeft.value = props.x_start + "px";
});

const handleClick = () => {
  emit("currentRow_update", 0, 100);
};

const onActivated = () => {
  selectItem.value = props;
  emit("select_update", props);
  console.log("onActivatedonActivated", selectItem.value);
};

const onResizestop = (param) => {
  console.log("******onResizestop******", param);
  let s = props.x_start,
    e = props.x_end;
  // 左右改变
  const { left, width } = param;
  if (left === 0) {
    // 右侧改变
    e = s + width;
  } else {
    // 左侧改变
    s = s + left;
  }
  console.log("处理之后的开始结束坐标", s, e);
  emit("size_update", s, e);
  dragKey.value += 1;
};
const onDragstop = (param) => {
  console.log("******onDragstop******", param);
  const { left, top } = param;
  //   求绝对值
  if (Math.abs(top) >= height.value) {
    console.log("移除当前项", parseInt(top / height.value));
    // 跨行
    emit(
      "enjambment_update",
      props.x_start + left,
      props.x_end + left,
      parseInt(top / height.value) // 跨行数（正先下跨行，负向上跨行）
    );
  } else {
    emit("currentRow_update", props.x_start + left, props.x_end + left);
  }
  if (left !== 0) {
    dragKey.value += 1;
  }
};
</script>

<style lang="scss" scoped>
.rowItem {
  position: absolute;
  left: v-bind(itemLeft);
  top: 0;
  .draggable {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background-color: #1890ff;
    box-sizing: border-box;
    box-shadow: 0 0 5px rgba($color: #989da1, $alpha: 0.8);
    border-radius: 2px;
    div {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
